Database Backup

I am listing here the PHP script to generate backup of database.

<?php
/* Database Backup */
$username = "dbusername";  //database username
$password = 'dbpass';   //database password
$hostname = "localhost";  //host
$dbname = "dbname"; //databse name
$sConnString = mysql_connect($hostname, $username, $password) 
or die("Unable to connect to MySQL");

$name = '/pathtodirectory/db'.date('d-m-Y').'.sql.gz'; //give full path of the directory where the backup should be saved

//create a connection object 
$connection = mysql_select_db($dbname,$sConnString) 
or die("Could not select DB");

$command = "mysqldump -u$username -p$password $dbname | gzip > $name"; 
system($command);
echo "<br/>Database Backup Created successfully.";
?>

For saving the file with ‘sql’ extension replace the code as specified below at specified line numbers in the above code (Although ‘zip’ file will take less space).

$name = '/pathtodirectory/db'.date('d-m-Y').'.sql'; //line 10
$command = "mysqldump -u$username -p$password $dbname > $name"; //line 16

You can also set cron jobs for dumping databdase in the cpanel of your site.

Write this command with all the database details,

mysqldump -uusername -ppassword dbname > db.sql

2 thoughts on “Database Backup

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top